package com.wchat.server.handler;

import com.wchat.server.ClientManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : willian fu
 * @date : 2021/8/30
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class WebSocketHandHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Autowired
    private ClientManager clientManager;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            fullHttpRequestHandler(ctx, (FullHttpRequest) msg);
        }
        ctx.fireChannelRead(msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) throws Exception {
        /* if (frame instanceof PingWebSocketFrame) {
            pingWebSocketFrameHandler(ctx, (PingWebSocketFrame) frame);
        } else if (frame instanceof TextWebSocketFrame) {
            textWebSocketFrameHandler(ctx, (TextWebSocketFrame) frame);
        } else if (frame instanceof CloseWebSocketFrame) {
            closeWebSocketFrameHandler(ctx, (CloseWebSocketFrame) frame);
        }*/
        channelHandlerContext.fireChannelRead(webSocketFrame);
    }

    /**
     * 处理连接请求，客户端WebSocket发送握手包时会执行这一次请求
     *
     * @param ctx
     * @param request
     */
    private void fullHttpRequestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
        String uri = request.uri();
        log.debug("接收到客户端{}的握手包URL{}", ctx.channel().id(), uri);
        if (uri.startsWith("/wchat")){
            request.setUri("/wchat");
            String[] split = uri.split("/");
            clientManager.authentication(ctx.channel(), split[split.length - 1]);
        } else {
            ctx.close();
        }
    }
}
